package com.yang.webapi.module.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yang.security.utils.UserUtils;
import com.yang.service.api.UserService;
import com.yang.service.model.enums.ExceptionEnum;
import com.yang.service.model.vo.UserVO;
import com.yang.webapi.module.service.UserWebService;
import com.yang.webapi.module.utils.http.HttpAPIService;
import com.zhy.base.exception.DefaultException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Objects;


/**
 * Created by xin7k
 * Date: 15:03
 */
@Service
@Slf4j
public class UserWebServiceImpl implements UserWebService {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpAPIService httpAPIService;

    @Value("${wechat.url.accessToken}")
    private String accessTokenURL;


    @Override
    public UserVO weChatLogin(String code) {
        try {
            String at_url = accessTokenURL.replace("JSCODE", code);
            log.info("request wechat access token url : {}", at_url);
            String result = httpAPIService.doGet(at_url);
            log.info("request wechat access token result : {}", result);
            JSONObject accessToken;
            if (Objects.isNull(result) || Objects.nonNull((accessToken = JSONObject.parseObject(result)).getInteger("errcode"))) {
                throw DefaultException.newInstance(ExceptionEnum.GET_WECHAT_INFO_ERROR);
            }

            //用户此应用中唯一标识，全局微信唯一使用：unionId
            return userService.saveWeChatUser(accessToken.getString("openid"));
        }catch (Exception e){
            e.printStackTrace();
            throw DefaultException.newInstance(ExceptionEnum.USER_LOGIN_ERROR);
        }
    }

    @Override
    public UserVO getUserInfo() {
        String userId = UserUtils.getUserId();
        return userService.getUserInfo(userId);
    }
}
